/*
 * Copyright 2014 Red Hat, Inc.
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *  The Eclipse Public License is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  The Apache License v2.0 is available at
 *  http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

package com.motu.vertx.module.utility.webtool;

import com.motu.vertx.module.utility.mysql.MysqlTool;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.jdbc.JDBCAuth;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.sqlclient.Pool;
import io.vertx.redis.client.RedisAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author <a href="http://tfox.org">Tim Fox</a>
 */
public class MyLoginHandler extends BaseWebHandler/*implements FormLoginHandler*/ {

	private static final Logger logger = LoggerFactory.getLogger(MyLoginHandler.class);

	public static JDBCAuth authProvider;
	public static Pool jdbcClientWeb;
	public static RedisAPI redisClient;
	
	public static void init(JDBCAuth authProvider, Pool jdbcClientWeb, RedisAPI redisClient){
		MyLoginHandler.authProvider = authProvider;
		MyLoginHandler.jdbcClientWeb = jdbcClientWeb;
		MyLoginHandler.redisClient = redisClient;
	}

//	@Override
	public static void handle(RoutingContext context) {
		HttpServerRequest req = context.request();
		HttpServerResponse response = context.response();
		if (req.method() != HttpMethod.POST) {
			context.fail(405); // Must be a POST
		} else {
			JsonObject json = context.body().asJsonObject();
			String username = Aes.getDecryptPwd(json.getString("username"));
			String password = Aes.getDecryptPwd(json.getString("password"));
			if (username == null || password == null) {
				logger.warn("No username or password provided in form - did you forget to include a BodyHandler?");
				context.fail(400);
			} else {
				Session session = context.session();
				String sql2 = "select id,password,password_salt,webperms,bigames,depid,groupid,employeeid,relation,gameperms,platform,channel,account_type,enable from manager_users where username = ?;";
				JsonArray params2 = new JsonArray().add(username);
				MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql2,params2 , res->{
					if (res.succeeded()) {
						JsonArray resArray = res.result();
						if(resArray==null||resArray.isEmpty()) {
							sendHttpResponseError(response, "帐号不存在");
							return;
						}else if(resArray.getJsonObject(0).getInteger("enable") == 0) {
							sendHttpResponseError(response, "该用户被禁止登录，请联系管理员！");
							return;
						}else if(resArray.getJsonObject(0).getInteger("account_type") == 1) {
							sendHttpResponseError(response, "请使用企业微信登录");
							return;
						}
						String dbpwd = resArray.getJsonObject(0).getString("password");
						String dbsalt = resArray.getJsonObject(0).getString("password_salt");
						String chkpwd = authProvider.computeHash(password, dbsalt);
						if(!dbpwd.equalsIgnoreCase(chkpwd)) {
							sendHttpResponseError(response, "密码错误");
							return;
						}
						loginCallback(context,jdbcClientWeb,redisClient,username,resArray);
//						int id = resArray.getJsonObject(0).getInteger("id");
//						String webperms = resArray.getJsonObject(0).getString("webperms");
//						String gameperms = resArray.getJsonObject(0).getString("gameperms");
//						String bigames = resArray.getJsonObject(0).getString("bigames");
//						String relation = resArray.getJsonObject(0).getString("relation");
//						String platform = resArray.getJsonObject(0).getString("platform");
//						String channel = resArray.getJsonObject(0).getString("channel");
//						int depid = resArray.getJsonObject(0).getInteger("depid");
//						int groupid = resArray.getJsonObject(0).getInteger("groupid");
//						int employeeid = resArray.getJsonObject(0).getInteger("employeeid");
//						if (session != null) {
//							session.regenerateId();
//							String sql_role = "select role from manager_roles where username = ?;";  //角色列表
//							String sql_group = "select projectid, refuselist from webpages_group where groupid = ?;";//group资源限制
//							String sql_username = "select projectid, refuselist from webpages_username where username = ?;";//user资源限制
//							String sql_perms = "select id,projectid,isgameserver from webtype"; //游戏服务器权限列表
//							String projectidString = "";
//							if(gameperms != null&& !gameperms.isEmpty()) {
//								//去重 获取projectid
//								String[] tmp = gameperms.split(",");
//								for (int i=0 ; i < tmp.length ;i ++) {
//									String[] itmp = tmp[i].split("-");
//									if( projectidString.indexOf(itmp[0]) == -1) {
//										if(projectidString != "") {
//											projectidString += ",";
//										}
//										projectidString += itmp[0];
//									}
//								}
//								sql_perms += " where projectid in ("+projectidString+");";//游戏服务器权限列表(projectid)
//							}else {
//								sql_perms += " where false;";//列表为空，没有权限，不查询出数据
//							}
//							 							
//							JsonArray paramgroup = new JsonArray().add(groupid);
//							JsonArray paramsusername = new JsonArray().add(username);
//							Future<JsonArray> fut_role = MysqlUtils.queryJsonArrayFromDb(jdbcClientWeb, sql_role, paramsusername);
//							Future<JsonArray> fut_group = MysqlUtils.queryJsonArrayFromDb(jdbcClientWeb, sql_group, paramgroup);
//							Future<JsonArray> fut_username = MysqlUtils.queryJsonArrayFromDb(jdbcClientWeb, sql_username, paramsusername);
//							Future<JsonArray> fut_perms = MysqlUtils.queryJsonArrayFromDb(jdbcClientWeb, sql_perms, new JsonArray());
//							CompositeFuture.all(fut_role, fut_group, fut_username,fut_perms).onComplete(ar->{
//								if (ar.succeeded()) {
//									JsonArray rolelist = new JsonArray();   //角色列表
//									for(int i=0; i<fut_role.result().size();i++){
//										rolelist.add(fut_role.result().getJsonObject(i).getString("role"));
//									}
//									
//									JsonArray webpages = fut_group.result();   //资源限制列表，合并fut_group,fut_username结果
//									JsonArray webpages_username = fut_username.result();
//									for (int k=0; k<webpages_username.size(); k++) {
//										webpages.add(webpages_username.getJsonObject(k));
//									}
//									JsonArray gamepermsArray = new JsonArray();  //允许访问的游戏服务器类型
//									if(gameperms != null&& !gameperms.isEmpty()) {
//										for (String i  : gameperms.split(",")) {
//											gamepermsArray.add(i);
//										}
//									}
//									
//									JsonArray permArray = new JsonArray();  //允许访问的后台列表
//									if(webperms != null&& !webperms.isEmpty()) {
//										String webpermsTmp = webperms;
//										webpermsTmp = webpermsTmp.replace("[","");
//										webpermsTmp = webpermsTmp.replace("]","");
//										JsonArray permlist = fut_perms.result();
//																						
//										//gameperms权限整合
//										if(gamepermsArray.size() != 0) {  
//											for (int i=0; i<permlist.size();i++ ) {
//												JsonObject tmp = permlist.getJsonObject(i);
//												String tmpString = tmp.getInteger("projectid") + "-" + tmp.getInteger("isgameserver");
//												if(gameperms.indexOf(tmpString) != -1 && webpermsTmp.indexOf(tmp.getInteger("id").toString()) == -1 ) {
//													webpermsTmp += ",";
//													webpermsTmp += tmp.getInteger("id");
//												}
//											}
//										}		
//										webpermsTmp = "[" + webpermsTmp + "]";
//										permArray = new JsonArray(webpermsTmp);
//									}
//
//									JsonArray bigamesArray = new JsonArray();  //允许访问的bi游戏列表
//									if(bigames != null&& !bigames.isEmpty()) {
//										bigamesArray = new JsonArray(bigames);
//										
//									}
//									JsonArray relationArr = new JsonArray();  //账号关联者列表
//									if (relation != null && !relation.isEmpty()) {
//										relationArr = new JsonArray(relation);
//									}
//									JsonObject result = new JsonObject();
//									result.put("success", true);
//									String token = context.getCookie("vertx-web.session").getValue();
//									result.put("id",id);
//									result.put("token",token);
//									result.put("rolelist", rolelist);
//									result.put("webpages", webpages);
//									result.put("webperms", permArray);
//									result.put("gameperms", gamepermsArray);
//									result.put("bigames", bigamesArray);
//									result.put("relation", relationArr);
//									result.put("platform", platform);
//									result.put("channel", channel);
//									result.put("depid", depid);
//									result.put("employeeid", employeeid);
//									result.put("name", username);
//									sendHttpResponse(response, result);
//									
//									//更新reidis里的登录信息，更新touken
//									String key = RedisUtils.getWebUserTokenKey(username,token);
//									JsonObject obj = new JsonObject().put("tokentime", Tool.getCurTime());
//									obj.put("checktime", Tool.getCurTime()); //检测时间 
//									obj.put("rolelist", rolelist.toString());
//									obj.put("webperms", permArray.toString());
//									obj.put("bigames", bigamesArray.toString());
//									RedisTools.setHashJsonObject(redisClient, key, obj);
//									RedisTools.expire(redisClient, key, BaseWebHandler.TOKEN_ACCESS_TIME);
//									String sql = "insert into manager_token(username,token,tokentime) values(?,?,?);";
//									JsonArray params = new JsonArray().add(username).add(token).add(Tool.getCurTime());
//									MysqlUtils.updateToDb(jdbcClientWeb, sql, params, res1->{});
//								} else {
//									sendHttpResponseError(response, ar.cause().getMessage());
//								}
//							});
//						}
					} else {
						sendHttpResponseError(response, res.cause().getMessage());
					}
				});
			}
		}
	}
}
